package com.fy.controller;


import cn.hutool.json.JSONUtil;
import com.fy.entity.Result;
import com.fy.entity.User;
import com.fy.service.IUserService;
import com.fy.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 晓岩
 * @since 2022-06-06
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    IUserService userService;
    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    RedisTemplate redisTemplate;
    @RequestMapping("mylogin")
    public Result mylogin(@RequestBody User user){
        System.out.println("111111111111111111111111111111111111111111111111");
        System.out.println("user is"+user);
        UsernamePasswordAuthenticationToken uptoken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        try{
            Authentication authentication = authenticationManager.authenticate(uptoken);
            User loginUser = (User)authentication.getPrincipal();
            String token = JwtUtils.createToken(loginUser.getUsername(), 30, JSONUtil.toJsonStr(loginUser));
            redisTemplate.opsForValue().set(loginUser.getUsername(),authentication,30, TimeUnit.MINUTES);
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            map.put("userInfo",loginUser);
            return new Result(200,"登录成功",map);
        }catch (Exception e){
            return new Result(201,"登录失败",e);
        }
    }
}
